package com.tubeonfire.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.tubeonfire.entity.Category;
import com.tubeonfire.entity.Playlist;
import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.CategoryModel;
import com.tubeonfire.model.PlaylistModel;
import com.tubeonfire.model.TubeModel;
import com.tubeonfire.util.StringHelper;

public class AdCategoryController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String path = ((HttpServletRequest) request).getRequestURI();
		String action = "";
		String[] splittedURI = path.split("/");
		// if length = 3, this is for action request.
		if (splittedURI.length == 4) {
			action = splittedURI[splittedURI.length - 1];
			System.out.println("Do action : " + action);
			// create new category, return create page.
			if (action.equalsIgnoreCase("manager")) {
				List<Category> result = CategoryModel.all();
				if (result != null && result.size() > 0) {
					request.setAttribute("result", result);
					request.getRequestDispatcher("/category_manager.jsp")
							.forward(request, response);
				} else {
					response.getWriter()
							.println("Category table have no item.");
				}
			}
			// create category.
			else if (action.equalsIgnoreCase("create")) {
				request.getRequestDispatcher("/category_create.jsp").forward(
						request, response);
			}
			// edit category.
			else if (action.equalsIgnoreCase("edit")) {
				response.getWriter().println("Edit.");
			}
			// delete category.
			else if (action.equalsIgnoreCase("delete")) {
				String id = request.getParameter("id");
				if (id != null) {
					Category cate = CategoryModel.getByCateAlias(id);
					if (cate != null) {
						cate.setStatus(4);
						CategoryModel.update(cate);
						CategoryModel.closePM();
						response.getWriter().println("Deleted.");
					} else {
						response.getWriter().println("Category is not exits.");
					}

				} else {
					response.getWriter().println(
							"Invalid category. Please try again.");
				}
			}// edit list clips in category.
			else if (action.equalsIgnoreCase("edit_videos")) {
				response.getWriter().println("Edit video.");
			}
			// add clips to category.
			else if (action.equalsIgnoreCase("add_video")) {
				String tubeId = request.getParameter("tubeId");
				String categoryAlias = request.getParameter("categoryAlias");
				Tube tub = TubeModel.getByTubeId(tubeId);
				Category cate = CategoryModel.getByCateAlias(categoryAlias);
				if (tub != null && cate != null) {
					List<Text> listTubes = new ArrayList<Text>();
					if (cate.getListTubes().size() > 0) {
						listTubes = cate.getListTubes();
					}					
					for (int i = 0; i < listTubes.size(); i++) {
						if (listTubes.get(i).equals(tub.getTubeId())) {
							listTubes.remove(i);
							break;
						}
					}
					listTubes.add(new Text(tub.toString()));
					cate.setListTubes(listTubes);
					CategoryModel.update(cate);
					CategoryModel.closePM();
					System.out.println("Ok, video added to playlist");

				} else {
					response.getWriter().println(
							"Tube or category are not exits.");
				}
				response.getWriter().println("Add video to category.");
			}
		}
		// if length = 4, this is view detail playlist request.
		else if (splittedURI.length == 5) {
			response.getWriter().println("Length = 5.");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user != null) {
			String action = req.getParameter("action");
			if (action.equalsIgnoreCase("create")) {
				Category cate = new Category();
				if (req.getParameter("title") != null) {
					cate.setTitle(new Text(req.getParameter("title")));
				}
				if (req.getParameter("description") != null) {
					cate.setDescription(new Text(req
							.getParameter("description")));
				}
				Map<String, List<BlobKey>> blobs = blobstoreService
						.getUploads(req);
				List<BlobKey> blobKeys = blobs.get("myFile");
				if (blobKeys != null && blobKeys.size() > 0) {
					cate.setThumbImageUrl(new Text(blobKeys.get(0)
							.getKeyString()));
				}
				cate.setCount(0);
				cate.setStatus(1);
				cate.setAlias(StringHelper.getAliasByLanguage(req
						.getParameter("title")));
				CategoryModel.add(cate);
				resp.sendRedirect("/admin/category/manager");

			} else if (action.equalsIgnoreCase("edit")) {
				resp.getWriter().println("Edit Category");
			}
		} else {
			System.out.println("User is not login.");
			resp.sendRedirect("/login");
		}
	}
}
